package com.yeqiangwei.commons.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 解决拼音多音字问题
 * @author aroot
 *
 */
public class PinyinDictionary {

	private static final String PATH_DEFAULT = "/com/yeqiangwei/commons/util/pinyin.dic";
	
	private static PinyinDictionary singleton;
	
	private static Map<String, Map<String, String>> DIC = null;
	
	static {
		singleton = new PinyinDictionary();
	}
	
	private PinyinDictionary() {
		DIC = new HashMap<String, Map<String,String>>();
		try {
			loadDefault();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String toPinyin(String word, String letter, String defaultStr) {
		if(DIC.get(word) == null) {
			return defaultStr;
		}
		String string = DIC.get(word).get(letter);
		if(string != null) {
			return string;
		}
		else {
			return defaultStr;
		}
	}
	
	public final static PinyinDictionary getInstance() {
		return singleton;
	}
	
	private void loadDefault() throws Exception {
		 InputStream is = PinyinDictionary.class.getResourceAsStream(PATH_DEFAULT);
		 BufferedReader br = new BufferedReader(new InputStreamReader(is , "UTF-8"), 512);
		 String line;
		 do {
			 line = br.readLine();
			 String[] w = line.split(",");
			 if(ValidatorHelper.isEmpty(w) || w.length != 3) {
				 continue;
			 }
			 if(DIC.get(w[0]) == null) {
				 Map<String, String> M = new HashMap<String, String>();
				 M.put(w[1], w[2]);
				 DIC.put(w[0], M); 
			 }
			 else {
				 DIC.get(w[0]).put(w[1], w[2]);
			 }
		 }
		 while(line != null);
	}
}
